package com.zenithmind.mall.service.impl;

import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.exception.BusinessException;
import com.zenithmind.mall.mapper.ProductMapper;
import com.zenithmind.mall.mapper.ProductStockMapper;
import com.zenithmind.mall.mapper.ProductStatisticsMapper;
import com.zenithmind.mall.mapper.ProductSeoMapper;
import com.zenithmind.mall.pojo.dto.ProductDTO;
import com.zenithmind.mall.pojo.entity.Product;
import com.zenithmind.mall.pojo.entity.ProductStock;
import com.zenithmind.mall.pojo.entity.ProductStatistics;
import com.zenithmind.mall.pojo.entity.ProductSeo;
import com.zenithmind.mall.service.ProductManagementService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品管理服务实现类 - 遵循单一职责原则，专门负责商品的管理操作
 * 
 * @author ZenithMind Team
 * @since 2025-07-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductManagementServiceImpl implements ProductManagementService {

    private final ProductMapper productMapper;
    private final ProductStockMapper productStockMapper;
    private final ProductStatisticsMapper productStatisticsMapper;
    private final ProductSeoMapper productSeoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createProduct(ProductDTO productDTO) {
        validateProductData(productDTO);
        
        // 创建商品基本信息
        Product product = new Product();
        BeanUtils.copyProperties(productDTO, product);
        product.setCreateBy(UserContext.getUserId());
        
        if (productMapper.insert(product) <= 0) {
            throw new BusinessException("创建商品失败");
        }
        
        String productId = product.getId();
        
        // 创建库存信息
        createProductStock(productId, productDTO);
        
        // 创建统计信息
        createProductStatistics(productId);
        
        // 创建SEO信息
        createProductSeo(productId, productDTO);
        
        log.info("创建商品成功: {}", productId);
        return productId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateProduct(String id, ProductDTO productDTO) {
        Product existingProduct = productMapper.selectById(id);
        if (existingProduct == null) {
            throw new BusinessException("商品不存在");
        }
        
        validateProductData(productDTO);
        
        // 更新商品基本信息
        Product product = new Product();
        BeanUtils.copyProperties(productDTO, product);
        product.setId(id);
        product.setUpdateBy(UserContext.getUserId());
        
        if (productMapper.updateById(product) <= 0) {
            throw new BusinessException("更新商品失败");
        }
        
        // 更新库存信息
        updateProductStock(id, productDTO);
        
        // 更新SEO信息
        updateProductSeo(id, productDTO);
        
        log.info("更新商品成功: {}", id);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteProduct(String id) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        
        // 检查商品是否可以删除（例如：是否有未完成的订单）
        if (product.isOnSale()) {
            throw new BusinessException("上架中的商品不能删除，请先下架");
        }
        
        // 软删除商品及相关信息
        if (productMapper.deleteById(id) <= 0) {
            throw new BusinessException("删除商品失败");
        }
        
        // 删除相关信息
        productStockMapper.deleteById(id);
        productStatisticsMapper.deleteById(id);
        productSeoMapper.deleteById(id);
        
        log.info("删除商品成功: {}", id);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteProducts(List<String> ids) {
        for (String id : ids) {
            if (!deleteProduct(id)) {
                throw new BusinessException("批量删除商品失败: " + id);
            }
        }
        
        log.info("批量删除商品成功: {}", ids);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean onShelf(String id) {
        return updateProductStatus(id, "1"); // 上架
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean offShelf(String id) {
        return updateProductStatus(id, "0"); // 下架
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateProductStatus(String id, String status) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        
        // 验证状态变更的合法性
        validateStatusChange(product, Integer.parseInt(status));
        
        Product updateProduct = new Product();
        updateProduct.setId(id);
        updateProduct.setStatus(Integer.parseInt(status));
        updateProduct.setUpdateBy(UserContext.getUserId());
        
        if (productMapper.updateById(updateProduct) <= 0) {
            throw new BusinessException("更新商品状态失败");
        }
        
        log.info("更新商品状态成功: {} -> {}", id, status);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchOnShelf(List<String> ids) {
        for (String id : ids) {
            if (!onShelf(id)) {
                throw new BusinessException("批量上架商品失败: " + id);
            }
        }
        
        log.info("批量上架商品成功: {}", ids);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchOffShelf(List<String> ids) {
        for (String id : ids) {
            if (!offShelf(id)) {
                throw new BusinessException("批量下架商品失败: " + id);
            }
        }
        
        log.info("批量下架商品成功: {}", ids);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String copyProduct(String id) {
        Product originalProduct = productMapper.selectById(id);
        if (originalProduct == null) {
            throw new BusinessException("原商品不存在");
        }
        
        // 复制商品基本信息
        Product newProduct = new Product();
        BeanUtils.copyProperties(originalProduct, newProduct);
        newProduct.setId(null);
        newProduct.setName(originalProduct.getName() + " (复制)");
        newProduct.setStatus(0); // 默认下架状态
        newProduct.setCreateBy(UserContext.getUserId());
        
        if (productMapper.insert(newProduct) <= 0) {
            throw new BusinessException("复制商品失败");
        }
        
        String newProductId = newProduct.getId();
        
        // 复制库存信息
        copyProductStock(id, newProductId);
        
        // 复制统计信息（重置为0）
        createProductStatistics(newProductId);
        
        // 复制SEO信息
        copyProductSeo(id, newProductId);
        
        log.info("复制商品成功: {} -> {}", id, newProductId);
        return newProductId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean importProducts(List<ProductDTO> productDTOs) {
        for (ProductDTO productDTO : productDTOs) {
            try {
                createProduct(productDTO);
            } catch (Exception e) {
                log.error("导入商品失败: {}", productDTO.getName(), e);
                throw new BusinessException("导入商品失败: " + productDTO.getName());
            }
        }
        
        log.info("批量导入商品成功，数量: {}", productDTOs.size());
        return true;
    }

    /**
     * 验证商品数据
     */
    private void validateProductData(ProductDTO productDTO) {
        if (productDTO.getName() == null || productDTO.getName().trim().isEmpty()) {
            throw new BusinessException("商品名称不能为空");
        }
        
        if (productDTO.getCategoryId() == null || productDTO.getCategoryId().trim().isEmpty()) {
            throw new BusinessException("商品分类不能为空");
        }
        
        if (productDTO.getPrice() == null || productDTO.getPrice().compareTo(java.math.BigDecimal.ZERO) <= 0) {
            throw new BusinessException("商品价格必须大于0");
        }
    }

    /**
     * 验证状态变更的合法性
     */
    private void validateStatusChange(Product product, Integer newStatus) {
        // 上架时检查必要条件
        if (newStatus == 1) {
            if (!product.hasValidPrice()) {
                throw new BusinessException("商品价格无效，无法上架");
            }
            if (!product.hasValidSku()) {
                throw new BusinessException("商品SKU无效，无法上架");
            }
        }
    }

    /**
     * 创建商品库存信息
     */
    private void createProductStock(String productId, ProductDTO productDTO) {
        ProductStock stock = new ProductStock();
        stock.setProductId(productId);
        stock.setStock(productDTO.getStock() != null ? productDTO.getStock() : 0);
        stock.setLowStock(productDTO.getLowStock() != null ? productDTO.getLowStock() : 0);
        stock.setLockedStock(0);
        stock.setVersion(0);
        stock.setCreateBy(UserContext.getUserId());
        
        productStockMapper.insert(stock);
    }

    /**
     * 创建商品统计信息
     */
    private void createProductStatistics(String productId) {
        ProductStatistics statistics = new ProductStatistics();
        statistics.setProductId(productId);
        statistics.setSalesCount(0);
        statistics.setViewCount(0);
        statistics.setFavoriteCount(0);
        statistics.setReviewCount(0);
        statistics.setPositiveReviewCount(0);
        statistics.setAverageRating(0.0);
        statistics.setIsRecommend(0);
        statistics.setIsNew(1);
        statistics.setIsHot(0);
        statistics.setCreateBy(UserContext.getUserId());
        
        productStatisticsMapper.insert(statistics);
    }

    /**
     * 创建商品SEO信息
     */
    private void createProductSeo(String productId, ProductDTO productDTO) {
        ProductSeo seo = new ProductSeo();
        seo.setProductId(productId);
        seo.setSeoTitle(productDTO.getName());
        seo.setKeywords(productDTO.getKeywords());
        seo.setSeoDescription(productDTO.getSeoDescription());
        seo.setSeoEnabled(1);
        seo.setCreateBy(UserContext.getUserId());
        
        productSeoMapper.insert(seo);
    }

    /**
     * 更新商品库存信息
     */
    private void updateProductStock(String productId, ProductDTO productDTO) {
        ProductStock stock = productStockMapper.selectById(productId);
        if (stock != null) {
            if (productDTO.getStock() != null) {
                stock.setStock(productDTO.getStock());
            }
            if (productDTO.getLowStock() != null) {
                stock.setLowStock(productDTO.getLowStock());
            }
            stock.setUpdateBy(UserContext.getUserId());
            productStockMapper.updateById(stock);
        }
    }

    /**
     * 更新商品SEO信息
     */
    private void updateProductSeo(String productId, ProductDTO productDTO) {
        ProductSeo seo = productSeoMapper.selectById(productId);
        if (seo != null) {
            seo.setSeoTitle(productDTO.getName());
            seo.setKeywords(productDTO.getKeywords());
            seo.setSeoDescription(productDTO.getSeoDescription());
            seo.setUpdateBy(UserContext.getUserId());
            productSeoMapper.updateById(seo);
        }
    }

    /**
     * 复制商品库存信息
     */
    private void copyProductStock(String originalProductId, String newProductId) {
        ProductStock originalStock = productStockMapper.selectById(originalProductId);
        if (originalStock != null) {
            ProductStock newStock = new ProductStock();
            BeanUtils.copyProperties(originalStock, newStock);
            newStock.setId(null);
            newStock.setProductId(newProductId);
            newStock.setLockedStock(0); // 重置锁定库存
            newStock.setVersion(0); // 重置版本号
            newStock.setCreateBy(UserContext.getUserId());
            productStockMapper.insert(newStock);
        }
    }

    /**
     * 复制商品SEO信息
     */
    private void copyProductSeo(String originalProductId, String newProductId) {
        ProductSeo originalSeo = productSeoMapper.selectById(originalProductId);
        if (originalSeo != null) {
            ProductSeo newSeo = new ProductSeo();
            BeanUtils.copyProperties(originalSeo, newSeo);
            newSeo.setId(null);
            newSeo.setProductId(newProductId);
            newSeo.setCreateBy(UserContext.getUserId());
            productSeoMapper.insert(newSeo);
        }
    }
}
